<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">云教育后台管理系统</h3>
        <el-image class="img" :src="imgs" />
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>

      <el-form-item prop="verifycode">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          ref="verifycode"
          v-model="loginForm.verifycode"
          type="text"
          placeholder="验证码"
          tabindex="3"
          name="verifycode"
          @keyup.enter.native="handleLogin"
        />
        <!-- 验证码图片 -->
        <el-image
          class="captcha-img"
          :src="captchaImg"
          alt="验证码"
          @click="refreshCaptcha"
          title="点击刷新"
        />
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
      >
        登录
      </el-button>

      <div class="tips">
        <span style="margin-right: 20px">username: admin</span>
        <span> password: any</span>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    const validatePassword = (rule, value, callback) => {
      // 拿到密码后先判断长度，再加密，最后发送请求获取返回值
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"));
      } else {
        callback(); // callback() 必须这样写
      }
    };

    return {
      loginForm: {
        username: "super_admin",
        password: "vincet_86000",
        verifycode: "",
        loginKey: "" // 登录KEY
      },
      loginRules: {
        // 表单验证规则
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
          {
            required: true,
            trigger: "blur",
            message: "用户名格式不符，请重新输入",
            pattern: "^[a-zA-Z0-9_]{3,16}$", // 用户名（允许字母、数字、下划线，3到16位）
          },
        ],
        loginKey: [
          { required: true, trigger: "blur", message: "验证码失效，点击重新获取验证码" }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ],
        verifycode: [
          {
            required: true,
            trigger: "blur",
            message: "请输入4位验证码",
            pattern: "^[a-zA-Z0-9]{4}$", // 验证码规则
          },
        ],
      },
      loading: false,
      passwordType: "password", // 默认密码框类型
      redirect: undefined, // 登录后是否跳转
      imgs: require("@/assets/logo.png"), // 使用 @/ 符号来正确解析图片路径
      captchaImg: "", // 用来存放验证码图片的 URL
    };
  },
  watch: {
    $route: {
      handler(route) {
        this.redirect = route.query && route.query.redirect; // 如果有 redirect 跳转链接，登录后就跳转
      },
      immediate: true, // 一进来就执行
    },
  },
    mounted() {
    // 初始加载验证码图片
    this.refreshCaptcha();
  },
  methods: {
    showPwd() {
      // 切换密码显示和隐藏
      if (this.passwordType === "password") {
        this.passwordType = ""; // 显示密码
      } else {
        this.passwordType = "password"; // 隐藏密码
      }
      this.$nextTick(() => {
        // DOM 更新后执行获取焦点
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      // 表单验证并提交
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              // 登录成功后跳转
              this.$router.push({ path: this.redirect || "/" });
              this.loading = false;
            })
            .catch(() => {
              this.refreshCaptcha()
              this.loading = false
            });
        } else {
          return false;
        }
      });
    },
    refreshCaptcha() {
      this.$store.dispatch('user/getGraphic').then((data) => {
        this.captchaImg = data.img;
        this.loginForm.loginKey = data.loginKey;
      });
    }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调和光标变色 */
/* 详细见 https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .captcha-img {
  position: absolute;
  top: 50%;
  right: 0px; /* 调整右侧的位置 */
  transform: translateY(-50%);
  cursor: pointer;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 20px auto;
      text-align: center;
      font-weight: bold;
    }
    .img {
      margin: 0px auto 20px auto;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
